package com.yhyvr.api.service.store;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lz.kit.LogKit;
import com.lz.mybatis.generator.util.StringUtil;
import com.lz.mybatis.jdbc.auto.dao.*;
import com.lz.mybatis.jdbc.auto.model.*;
import com.lz.tool.*;
import com.lz.tool.aliupload.MediaUploadClient;
import com.yhyvr.api.service.wx.WxService;
import com.yhyvr.pojo.exception.ApiException;
import com.yhyvr.api.handle.AuthAnnotation;
import com.yhyvr.constant.WxUrlConstant;
import com.yhyvr.pojo.req.api.ApiReqBody;
import com.yhyvr.pojo.req.api.ApiReqData;
import com.yhyvr.pojo.req.api.store.user.*;
import com.yhyvr.pojo.resp.api.wx.AccessToken;
import com.yhyvr.pojo.resp.api.wx.WeiXinUserInfoResp;
import com.yhyvr.pojo.resp.api.ApiRespBody;
import com.yhyvr.pojo.resp.api.ApiRespData;
import com.yhyvr.pojo.resp.api.ApiResultCode;
import com.yhyvr.pojo.resp.api.user.ApiUserInfoResp;
import com.yhyvr.pojo.resp.api.user.login.LoginResp;
import com.yhyvr.service.SmsService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;


/**
 * Created by tech6 on 2016/10/11.
 * 代理商
 */
@Service
public class ApiProxyService {
    @Resource
    private BoProxyMapper boProxyMapper;
    @Resource
    private BoProxyBindMapper boProxyBindMapper;
    @Resource
    private SmsService smsService;
    @Resource
    private WxService wxService;
    @Resource
    private BoTasterMapper boTasterMapper;
    @Resource
    private BoAppFeedbackMapper boAppFeedbackMapper;
    /**
     * 注册用户
     * @param apiStoreRegisterReqApiReqData
     * @return
     */
    public ApiRespData<ApiRespBody> register(ApiReqData<ApiStoreRegisterReq> apiStoreRegisterReqApiReqData){
        ApiStoreRegisterReq apiStoreRegisterReq = apiStoreRegisterReqApiReqData.getBody();
        //验证验证码是否正确
        if(!smsService.validateCode(apiStoreRegisterReq.getPhone(),apiStoreRegisterReq.getVerificationCode())){
            return ApiRespData.buildFailErrorCode(ApiResultCode.FAIL,"1002","验证码验证失败！请重试！");
        }
        BoProxyExample boProxyExample = new BoProxyExample();
        boProxyExample.createCriteria().andBoProxyPhoneEqualTo(apiStoreRegisterReq.getPhone());
        if(boProxyMapper.countByExample(boProxyExample)>0){
            return ApiRespData.buildFailErrorCode(ApiResultCode.FAIL,"1001","该手机号已经被注册，请直接登录");
        }else{
            BoProxy boProxy = new BoProxy();
            boProxy.setBoProxyId(UUIDTool.getUUID());
            boProxy.setBoProxyType(0);
            boProxy.setBoProxyState(1);
            boProxy.setCreateTime(new Date());
            boProxy.setBoProxyNickName("用户:"+UUIDTool.getUUID().substring(0,10));
            boProxy.setBoProxyPhone(apiStoreRegisterReq.getPhone());
            boProxy.setBoProxyPassword(MD5.MD5Encode(apiStoreRegisterReq.getPassword()));
            boProxyMapper.insert(boProxy);
        }
        return ApiRespData.buildSucc();
    }
    /**
     * 绑定手机
     * @param apiStoreRegisterReqApiReqData
     * @return
     */
    @Transactional
    @AuthAnnotation(iLogin = true)
    public ApiRespData<ApiRespBody> bindPhone(ApiReqData<ApiStoreBindPhoneReq> apiStoreRegisterReqApiReqData){
            ApiStoreBindPhoneReq apiStoreRegisterReq = apiStoreRegisterReqApiReqData.getBody();
            //验证验证码是否正确
            if (!smsService.validateCode(apiStoreRegisterReq.getPhone(), apiStoreRegisterReq.getVerificationCode())) {
                return ApiRespData.buildFailErrorCode(ApiResultCode.FAIL, "2002", "验证码验证失败！请重试！");
            }
            BoProxyExample boProxyExample = new BoProxyExample();
            boProxyExample.createCriteria().andBoProxyPhoneEqualTo(apiStoreRegisterReq.getPhone());
            if (boProxyMapper.countByExample(boProxyExample) > 0) {
                return ApiRespData.buildFailErrorCode(ApiResultCode.FAIL, "2001", "该手机号已经被使用");
            } else {
                BoProxy boProxy = boProxyMapper.selectByPrimaryKey(apiStoreRegisterReqApiReqData.getCookieUserId());
                boProxy.setBoProxyPhone(apiStoreRegisterReq.getPhone());
                boProxyMapper.updateByPrimaryKey(boProxy);
            }
            return ApiRespData.buildSucc();
    }
    /**
     * 登录
     * @param apiStoreRegisterReqApiReqData
     * @return
     */
    public ApiRespData<LoginResp> loginWx(ApiReqData<LoginReq> apiStoreRegisterReqApiReqData){
        LoginReq apiStoreRegisterReq = apiStoreRegisterReqApiReqData.getBody();
        BoProxyExample boProxyExample = new BoProxyExample();
        boProxyExample.createCriteria().andBoProxyPhoneEqualTo(apiStoreRegisterReq.getPhone()).andBoProxyPasswordEqualTo(MD5.MD5Encode(apiStoreRegisterReq.getPassword()));
        BoProxy boProxy = ListUtils.getFirst(boProxyMapper.selectByExample(boProxyExample));
        if(boProxy!=null){
            LoginResp loginResp = new LoginResp();
            loginResp.setUserId(boProxy.getBoProxyId());
            return ApiRespData.buildSucc(loginResp);
        }else{
            return ApiRespData.buildFailErrorCode(ApiResultCode.FAIL,"60001","账号或密码不正确");
        }
    }
    /**
     * 登录
     * @param apiStoreRegisterReqApiReqData
     * @return
     */
    public ApiRespData<LoginResp> login(ApiReqData<LoginReq> apiStoreRegisterReqApiReqData){
        LoginReq apiStoreRegisterReq = apiStoreRegisterReqApiReqData.getBody();
        BoProxyExample boProxyExample = new BoProxyExample();
        boProxyExample.createCriteria().andBoProxyPhoneEqualTo(apiStoreRegisterReq.getPhone()).andBoProxyPasswordEqualTo(MD5.MD5Encode(apiStoreRegisterReq.getPassword()));
        BoProxy boProxy = ListUtils.getFirst(boProxyMapper.selectByExample(boProxyExample));
        if(boProxy!=null){
            LoginResp loginResp = new LoginResp();
            loginResp.setUserId(boProxy.getBoProxyId());
            return ApiRespData.buildSucc(loginResp);
        }else{
           return ApiRespData.buildFailErrorCode(ApiResultCode.FAIL,"60001","账号或密码不正确");
        }
    }


    /**
     * 修改密码
     * @param apiStoreRegisterReqApiReqData
     * @return
     */
    public ApiRespData<ApiRespBody> updatePassword(ApiReqData<ApiUserPassWordUpdateReq> apiStoreRegisterReqApiReqData){

            ApiUserPassWordUpdateReq apiStoreRegisterReq = apiStoreRegisterReqApiReqData.getBody();
            //验证验证码是否正确
            if (false||!smsService.validateCode(apiStoreRegisterReq.getPhone(), apiStoreRegisterReq.getVerificationCode())) {
                return ApiRespData.buildFailErrorCode(ApiResultCode.FAIL, "1002", "验证码验证失败！请重试！");
            }else {
                    BoProxyExample boProxyExample = new BoProxyExample();
                    boProxyExample.createCriteria().andBoProxyPhoneEqualTo(apiStoreRegisterReq.getPhone());
                    BoProxy boProxy = ListUtils.getFirst(boProxyMapper.selectByExample(boProxyExample));
                    if(boProxy!=null){
                        boProxy.setBoProxyPassword(MD5.MD5Encode(apiStoreRegisterReq.getPassword()));
                        boProxyMapper.updateByPrimaryKey(boProxy);
                        return ApiRespData.buildSucc();
                    }else{
                        return ApiRespData.buildFailErrorCode(ApiResultCode.FAIL, "1003", "没有找到该账户");
                    }

            }
    }
    /**
     * 获取个人信息
     * @param apiReqBodyApiReqData
     * @return
     */
    @AuthAnnotation(iLogin = true)
    public ApiRespData<ApiUserInfoResp> userInfo(ApiReqData<ApiReqBody> apiReqBodyApiReqData){

                String proxyId =apiReqBodyApiReqData.getCookieUserId();
                BoProxy boProxy = boProxyMapper.selectByPrimaryKey(proxyId);
                if(boProxy!=null) {
                    ApiUserInfoResp apiUserInfoResp = new ApiUserInfoResp();
                    apiUserInfoResp.setHeadImage(boProxy.getBoProxyHeadImage());
                    apiUserInfoResp.setNickName(boProxy.getBoProxyNickName());
                    apiUserInfoResp.setPhone(boProxy.getBoProxyPhone());
                    apiUserInfoResp.setSex(boProxy.getBoProxySex());
                    apiUserInfoResp.setUserType(boProxy.getBoProxyType());
                    apiUserInfoResp.setPhoneSub(boProxy.getBoProxyPhone());

                    BoTasterExample boTasterExample = new BoTasterExample();
                    boTasterExample.createCriteria().andBoBpProxyIdEqualTo(boProxy.getBoProxyId());
                    BoTaster boTaster=ListUtils.getFirst(boTasterMapper.selectByExample(boTasterExample));
                    if(boTaster != null){
                        apiUserInfoResp.setIsTaster(boTaster.getBoStatus());
                    }else{
                        apiUserInfoResp.setIsTaster(0);
                    }

                    return ApiRespData.buildSucc(apiUserInfoResp);
                }else{
                    return ApiRespData.buildFailErrorCode(ApiResultCode.FAIL,"10001","没有找到该用户");
                }
    }


    /**
     * 修改
     * @param apiReqBodyApiReqData
     * @return
     */
    @AuthAnnotation(iLogin = true)
    public ApiRespData<ApiRespBody> updateUserInfo(ApiReqData<ApiUpdateUserInfoReq> apiReqBodyApiReqData){

            try {
                String proxyId =apiReqBodyApiReqData.getCookieUserId();
                ApiUpdateUserInfoReq apiUpdateUserInfoReq = apiReqBodyApiReqData.getBody();
                BoProxy boProxy = boProxyMapper.selectByPrimaryKey(proxyId);
                if(StringUtils.isNotBlank(apiUpdateUserInfoReq.getNickName())) {
                    boProxy.setBoProxyNickName(apiUpdateUserInfoReq.getNickName());
                }
                if(StringUtils.isNotBlank(apiUpdateUserInfoReq.getHeadImage())) {
                    boProxy.setBoProxyHeadImage(apiUpdateUserInfoReq.getHeadImage());
                }
                if(apiUpdateUserInfoReq.getSex()!=-1) {
                    boProxy.setBoProxySex(apiUpdateUserInfoReq.getSex());
                }
                boProxyMapper.updateByPrimaryKey(boProxy);
                return ApiRespData.buildSucc();
            } catch (Exception e) {
                throw new ApiException("解析用户信息失败！",0,apiReqBodyApiReqData.getHead().getCrossDomain());
            }
    }

    @Transactional
    /**
     * 微信第三方登录
     */
    public ApiRespData<LoginResp> threadLogin(String code){
        try {
            JSONObject snsParam = wxService.getSnsParam(code);
            String openid =snsParam.getString("openid");
            String access_token =snsParam.getString("access_token");
            BoProxyBindExample boProxyBindExample = new BoProxyBindExample();
            BoProxy boProxy = new BoProxy();
            boProxyBindExample.createCriteria().andBindTypeEqualTo("WX").andKeyidEqualTo(openid);
            if(boProxyBindMapper.countByExample(boProxyBindExample)==0){
                WeiXinUserInfoResp weiXinUserInfoResp = JSON.parseObject(OkHttpUtil.get(WxUrlConstant.getUserInfoUrl(access_token,openid)),WeiXinUserInfoResp.class);
              String pid= UUIDTool.getUUID();
                boProxy.setBoProxyId(pid);
                boProxy=packBoProxy(boProxy);
                boProxy.setBoProxySex(weiXinUserInfoResp.getSex()-1);
                boProxy.setBoProxyHeadImage(MediaUploadClient.uploadBuyUrl(weiXinUserInfoResp.getHeadimgurl()));
                boProxy.setBoProxyNickName(weiXinUserInfoResp.getNickname());
                BoProxyBind boProxyBind = new BoProxyBind();
                boProxyBind.setBindType("WX");
                boProxyBind.setCreateTime(new Date());
                boProxyBind.setKeyid(openid);
                boProxyBind.setProxyId(pid);
                boProxyBind.setStatus((short) 1);
                boProxyBind.setPbId(UUIDTool.getUUID());
                boProxyBindMapper.insertSelective(boProxyBind);
                boProxyMapper.insertSelective(boProxy);
            }else{
                BoProxyBind bind = ListUtils.getFirst(boProxyBindMapper.selectByExample(boProxyBindExample));
                boProxy =  boProxyMapper.selectByPrimaryKey(bind.getProxyId());
            }
            LoginResp loginResp = new LoginResp();
            loginResp.setUserId(boProxy.getBoProxyId());
            return ApiRespData.buildSucc(loginResp);
        } catch (IOException e1) {
            LogKit.error(e1.getMessage(),e1);
            return ApiRespData.buildFail();
        } catch (Exception e1) {
            LogKit.error(e1.getMessage(),e1);
            return ApiRespData.buildFail();
        }
    }
    /**
     * 验证码登录
     *
     * @param apiReqData
     * @return
     */
    @Transactional
    public ApiRespData<LoginResp> loginByCode(ApiReqData<PhpneCodeLoginReq> apiReqData) {
        PhpneCodeLoginReq loginReq = apiReqData.getBody();
        boolean isTrue=smsService.validateCode(loginReq.getUserPhoneNumber(), loginReq.getCode());
        if(isTrue){
            BoProxyExample memberQuery = new BoProxyExample();
            memberQuery.createCriteria().andBoProxyPhoneEqualTo(loginReq.getUserPhoneNumber()).andBoProxyTypeNotEqualTo(3);
            BoProxy boProxy=ListUtils.getFirst(boProxyMapper.selectByExample(memberQuery));
            if(boProxy==null){
                boProxy= new BoProxy();
                boProxy.setBoProxyPhone(loginReq.getUserPhoneNumber());
                boProxy.setBoProxySex(0);
                String id = UUIDTool.getUUID();
                String nickName="用户:"+ RandomTool.getCode(6,11);
                boProxy.setBoProxyNickName(nickName);
                boProxy.setBoProxyId(id);
                boProxy = packBoProxy(boProxy);
                boProxyMapper.insertSelective(boProxy);
            }else {
                // do nothing
            }
            LoginResp loginResp = new LoginResp();
            loginResp.setUserId(boProxy.getBoProxyId());
            return ApiRespData.buildSucc(loginResp);
        }else{
            return ApiRespData.buildFail(ApiResultCode.FAIL,"验证码不正确");
        }
    }

    /**
     *品鉴师申请
     *
     * @param apiReqData
     * @return
     */
    @AuthAnnotation(iLogin = true)
    @Transactional
    public ApiRespData<LoginResp> applyTaster(ApiReqData<ApiTasterApplyReq> apiReqData) {
        ApiTasterApplyReq applyReq = apiReqData.getBody();
        boolean isTrue=smsService.validateCode(applyReq.getMobile(), applyReq.getVerify());
        if(isTrue){

            if(applyReq.getIdentify_number().length() != 15 && applyReq.getIdentify_number().length() != 18){
                return ApiRespData.buildFail(ApiResultCode.FAIL,"请输入正确的身份证号码！");
            }
            String proxyId =apiReqData.getCookieUserId();
            BoProxy boProxy = boProxyMapper.selectByPrimaryKey(proxyId);
            if(boProxy!=null) {
                BoTasterExample boTasterExample = new BoTasterExample();
                boTasterExample.createCriteria().andBoBpProxyIdEqualTo(boProxy.getBoProxyId());
                BoTaster boTaster=ListUtils.getFirst(boTasterMapper.selectByExample(boTasterExample));
                if(boTaster != null){
                   if(boTaster.getBoStatus()==(short)1){
                       return ApiRespData.buildFail(ApiResultCode.FAIL,"已提交申请，等待审核！");
                   }else if(boTaster.getBoStatus()==(short)2){
                       return ApiRespData.buildFail(ApiResultCode.FAIL,"您已经是品鉴师！");
                   }
                   else if(boTaster.getBoStatus()==(short)3){
                       String phone=applyReq.getMobile();
                       if(StringUtils.isNotBlank(boProxy.getBoProxyPhone())){
                           if (!boProxy.getBoProxyPhone().equals(phone)){
                               return ApiRespData.buildFail(ApiResultCode.FAIL,"手机号不正确，请用注册或绑定的手机号申请！");
                           }
                       }
                       boProxy.setBoProxyPhone(phone);
                       boProxyMapper.updateByPrimaryKey(boProxy);

                       boTaster.setBoBpProxyId(boProxy.getBoProxyId());
                       boTaster.setBoIdentifyNum(applyReq.getIdentify_number());
                       boTaster.setBoTrueName(applyReq.getTrue_name());
                       short a=1;
                       boTaster.setBoStatus(a);
                       boTaster.setBoApplyTime(new Date());
                       boTasterMapper.updateByPrimaryKey(boTaster);

                       return ApiRespData.buildSucc();
                   }
                   else if(boTaster.getBoStatus()==(short)4){
                       return ApiRespData.buildFail(ApiResultCode.FAIL,"您已被禁止，请联系客服！");
                   }
                }else{

                    String phone=applyReq.getMobile();
                    if(StringUtils.isNotBlank(boProxy.getBoProxyPhone())){
                        if (!boProxy.getBoProxyPhone().equals(phone)){
                            return ApiRespData.buildFail(ApiResultCode.FAIL,"手机号不正确，请用注册或绑定的手机号申请！");
                        }
                    }
                    boProxy.setBoProxyPhone(phone);
                    boProxyMapper.updateByPrimaryKey(boProxy);

                    BoTaster new_boTaster=new BoTaster();
                    new_boTaster.setBoTasterId(UUIDTool.getUUID());
                    new_boTaster.setBoBpProxyId(boProxy.getBoProxyId());
                    new_boTaster.setBoIdentifyNum(applyReq.getIdentify_number());
                    new_boTaster.setBoTrueName(applyReq.getTrue_name());
                    short a=1;
                    new_boTaster.setBoStatus(a);
                    new_boTaster.setBoApplyTime(new Date());
                    boTasterMapper.insert(new_boTaster);
                    return ApiRespData.buildSucc();
                }

                return ApiRespData.buildFail(ApiResultCode.FAIL,"服务器异常！");
            }else{
                return ApiRespData.buildFailErrorCode(ApiResultCode.FAIL,"10001","没有找到该用户");
            }
        }else{
            return ApiRespData.buildFail(ApiResultCode.FAIL,"验证码不正确");
        }

    }


    /**
     *进入试吃系统
     *
     * @param apiReqData
     * @return
     */
    @AuthAnnotation(iLogin = true)
    @Transactional
    public ApiRespData<LoginResp> toTasterSystem(ApiReqData<ApiTasterApplyReq> apiReqData) {
        ApiTasterApplyReq applyReq = apiReqData.getBody();
            String proxyId =apiReqData.getCookieUserId();
            BoProxy boProxy = boProxyMapper.selectByPrimaryKey(proxyId);
            if(boProxy!=null) {
                BoTasterExample boTasterExample = new BoTasterExample();
                boTasterExample.createCriteria().andBoBpProxyIdEqualTo(boProxy.getBoProxyId());
                BoTaster boTaster=ListUtils.getFirst(boTasterMapper.selectByExample(boTasterExample));
                if(boTaster != null){

                }else{

                    return ApiRespData.buildSucc();
                }

                return ApiRespData.buildFail(ApiResultCode.FAIL,"服务器异常！");
            }else{
                return ApiRespData.buildFailErrorCode(ApiResultCode.FAIL,"10001","没有找到该用户");
            }

    }






    public BoProxy packBoProxy(BoProxy boProxy){
        boProxy.setCreateTime(new Date());
        boProxy.setBoProxyType(1);
        boProxy.setBoProxyPassword("000000");
        boProxy.setBoBanComment(0);
        boProxy.setBoProxyState(1);
        return boProxy;
    }

    public ApiRespData<ApiRespBody> feedBack(ApiReqData<ApiFeedBackReq> apiFeedBackReqApiReqData){
        ApiFeedBackReq apiFeedBackReq=  apiFeedBackReqApiReqData.getBody();
        BoAppFeedback boAppFeedback = new BoAppFeedback();
        boAppFeedback.setUserId(apiFeedBackReqApiReqData.getCookieUserId());
        boAppFeedback.setAppFeedbackId(UUIDTool.getUUID());
        boAppFeedback.setAppId("");
        boAppFeedback.setContactInfo(apiFeedBackReq.getContactInfo());
        boAppFeedback.setContent(apiFeedBackReq.getContent());
        boAppFeedback.setCreateTime(new Date());
        boAppFeedbackMapper.insertSelective(boAppFeedback);
        return ApiRespData.buildSucc();
    }

}

